<template>
  <div class="container" style="height: 100%;" ref="consDom">
    <el-row :gutter="10">
      <el-col :xs="24">
        <div ref="colDom" style="position: absolute;height: 100%;"></div>
        <!-- form -->
		<div class="devList-top">
			<span>{{$t('program.AD.label.number')}}</span>
			<el-form :model="form">
				<el-form-item prop="deptId">
					<treeselect v-model="form.deptId" :options="mapTreeData" :show-count="true" @input='treeValueChange'
						:placeholder="$t('program.AD.input.number')" style='width: 300px;' :disableFuzzyMatching='true'/>
				</el-form-item>
				<!-- 查询 -->
			</el-form>
		</div>			
        <el-row :span='16'>
          <el-form
            inline
            ref="queryForm"
            :model="queryParams"
            v-show="showSearch"
          >
            <!-- 查询条件 -->
            <el-form-item label="查询条件:" prop="fDescription">
              <el-input
                placeholder="输入设备名称查询"
                v-model="queryParams.fDescription"
                clearable
                style="width: 180px"
                maxlength="15"
                show-word-limit
              ></el-input>
            </el-form-item>
            <!-- 节目ID -->
            <el-form-item label="" prop="fPId">
              <el-input
                oninput="value=value.replace(/[^\d]/g,'')"
                placeholder="输入节目ID查询"
                v-model="queryParams.fPId"
                clearable
                maxlength="15"
                style="width: 180px"
                show-word-limit
                @input="handleQuery2"
              ></el-input>
            </el-form-item>
            <!-- 节目号 -->
            <el-form-item prop="fPNo">
              <el-input
                v-model="queryParams.fPNo"
                :placeholder="$t('program.AD.input.PNum')"
                clearable
                style="width: 180px"
                show-word-limit
                maxlength="15"
              ></el-input>
            </el-form-item>
            <!-- button -->
            <!-- 搜索 -->
            <el-button
              type="primary"
              icon="el-icon-search"
              v-hasPermi="['lgsv:send:search']"
              @click="handleQuery"
              >{{ $t('program.AD.button.search') }}</el-button
            >
            <!-- 重置 -->
            <el-button
              type="info"
              plain
              icon="el-icon-refresh"
              v-hasPermi="['lgsv:send:clearTime']"
              @click="resetQuery"
              >{{ $t('program.AD.button.reset') }}</el-button
            >
          </el-form>
          <!-- 隐藏搜索 刷新 显隐列工具 
        columns:显隐列做筛选功能
        -->
        </el-row>
        <!-- button -->
        <el-row class="mb5">
          <el-col :span="20">
            <!-- 导出 -->
            <el-button
              type="warning "
              plain
              :disabled="multiple"
              icon="el-icon-male"
              v-hasPermi="['lgsv:send:export']"
              >{{ $t('program.AD.button.export') }}</el-button
            >
            <!-- 节目下架 -->
            <el-button
              type="success"
              plain
              icon="el-icon-download"
              :disabled="sendShow && sendShow2"
              v-hasPermi="['lgsv:program:del']"
              @click="handPull"
            >
              {{ $t('program.list.button.down') }}
            </el-button>
          </el-col>
          <el-col :span="4">
            <right-toolbar
              :showSearch.sync="showSearch"
              :columns="columns"
              @queryTable="existPrograms"
            ></right-toolbar>
          </el-col>
        </el-row>
        <!-- tableData -->
        <el-table
          :data="tableData"
          ref="multipleTable"
          v-loading="loading"
          highlight-current-row
          v-if="isTable"
          :max-height="tableHeight"
          @selection-change="handleSelectionChange"
          border
          :default-sort="{ prop: 'fAddTime', order: 'descending' }"
        >
          <!-- checkbox多选框  align="center"-->
          <el-table-column type="selection" width="40" align="center" />
          <!-- 设备号 -->
          <el-table-column
            prop="fNumber"
            :label="$t('program.AD.table.number')"
            width="130"
            align="center"
            v-if="columns[0].visible"
          >
          </el-table-column>
          <!-- 设备名称 -->
          <el-table-column
            prop="fDescription"
            :label="$t('program.AD.table.name')"
            align="center"
            width="80"
            show-overflow-tooltip
            v-if="columns[1].visible"
          >
          </el-table-column>
          <!-- 节目ID -->
          <el-table-column
            prop="fPId"
            :label="$t('program.AD.table.PNum')"
            align="center"
            width="70"
            v-if="columns[2].visible"
          >
          </el-table-column>
          <!-- 节目号 -->
          <el-table-column
            prop="fPNo"
            :label="$t('program.AD.table.PNo')"
            align="center"
            width="90"
            sortable
            show-overflow-tooltip
            v-if="columns[3].visible"
          >
          </el-table-column>
          <!-- 节目标题 -->
          <el-table-column
            prop="fPTitle"
            :label="$t('program.AD.table.title')"
            align="center"
            width="80"
            show-overflow-tooltip
            v-if="columns[4].visible"
          >
          </el-table-column>
          <!-- 是否存在设备 -->
          <el-table-column
            prop="fIsExistCard"
            :label="$t('program.AD.table.exist')"
            align="center"
            width="110"
            :formatter="deviceFormatter"
            v-if="columns[5].visible"
          >
          </el-table-column>
          <!-- 节目开始时间 -->
          <el-table-column
            prop="fBeginTime"
            :label="$t('program.AD.table.start')"
            align="center"
            min-width="120"
            show-overflow-tooltip
            v-if="columns[6].visible"
          >
          </el-table-column>
          <!-- 节目结束时间 -->
          <el-table-column
            prop="fEndTime"
            :label="$t('program.AD.table.end')"
            align="center"
            min-width="120"
            show-overflow-tooltip
            v-if="columns[7].visible"
          >
          </el-table-column>
          <!-- 发送进度 -->
          <el-table-column
            prop="fTaskSpeed"
            :label="$t('program.AD.table.taskBag')"
            align="center"
            width="80"
            v-if="columns[8].visible"
          >
          </el-table-column>
          <!-- 发送状态 -->
          <el-table-column
            prop="fTaskStatus"
            :label="$t('program.AD.table.state')"
            align="center"
            :formatter="statusFormatter"
            width="80"
            v-if="columns[9].visible"
          >
          </el-table-column>
          <!-- 错误日志 -->
          <el-table-column
            prop="fTaskResult"
            :label="$t('program.AD.table.error')"
            align="center"
            width="80"
            show-overflow-tooltip
            v-if="columns[10].visible"
          >
          </el-table-column>
          <!-- 添加时间 -->
          <el-table-column
            prop="fAddTime"
            :label="$t('program.AD.table.add')"
            align="center"
            show-overflow-tooltip
            sortable
            min-width="160"
            v-if="columns[11].visible"
          >
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="existPrograms"
        />
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import { getDev } from '@/api/system/map'
import { pullProgram } from '@/api/system/program' //下架节目
import { treeselect } from '@/api/system/dept' // import treeselect api
import { exist } from '@/api/EditorProgram/advertising' // import request api
import Treeselect from '@riophae/vue-treeselect' // import the component
import '@riophae/vue-treeselect/dist/vue-treeselect.css' // import the styles
export default {
  name: 'EquipmentAds',
  components: { Treeselect },
  data () {
    return {
      form: {
        deptId: undefined
      },
      quer2: {
        deptId: undefined
      },
      dateRange: [], // 日期范围
      mapTreeData: [],
      isTable: false,
      tableHeight: 0,
      sendShow: true,
      total: 0, // 页码总条数
      sendList: [], // 发送列表
      deptName: undefined, // 部门名称
      deptOptions: undefined, // 部门树选项
      showSearch: true, // 显示搜索条件
      loading: false, // 遮罩层
      multiple: true, // 非多个checkbox禁用
      expandeds: [],
      defaultProps: {
        children: 'children', // 指定子树为节点对象的某个属性值
        label: 'label' // 指定节点标签为节点对象的某个属性值
      },
      // 发送记录查询模型
      queryParams: {
        deptId: undefined, // 部门id
        fNumber: undefined, // 设备编号
        fPNo: undefined, //节目号
        fDescription: undefined, // 设备名称
        taskStatus: undefined, // 发送状态
        beginTime: undefined, // 开始时间
        endTime: undefined, // 结束时间
        pageNum: 1, // 页码
        pageSize: 20, // 条数
        fPId: undefined //节目Id
      },
      querys: {
        deptId: undefined // 部门id
      },
      statusOptions: [
        {
          value: 0,
          label: '等待发送' // 等待发送
        },
        {
          value: 4,
          label: '成功' // 成功
        },
        {
          value: 10,
          label: '失败' // 失败
        },
        {
          value: 11,
          label: '任务覆盖' // 任务覆盖
        }
      ],
      // 表格显隐列信息
      columns: [
        { key: 0, label: `设备号`, visible: true },
        { key: 1, label: `设备名称`, visible: true },
        { key: 2, label: `节目ID`, visible: true },
        { key: 3, label: `节目号`, visible: true },
        { key: 4, label: `节目名称`, visible: true },
        { key: 5, label: `是否存在设备`, visible: true },
        { key: 6, label: `节目开始时间`, visible: true },
        { key: 7, label: `节目结束时间`, visible: true },
        { key: 8, label: `发送进度`, visible: true },
        { key: 9, label: `发送状态`, visible: true },
        { key: 10, label: `错误日志`, visible: true },
        { key: 11, label: `添加时间ID`, visible: true }
      ],
      tableData: undefined,
      // 选中数组
      ids: [],
      cards: [],
      sendShow2: true
    }
  },
  methods: {
    // currDeptChange(val){
    // 	if (val == null || val == undefined || val == '') {
    // 		return
    // 	}
    // 	if(val.length>8){
    // 		this.queryParams.fNumber=val
    // 		this.existPrograms()
    // 	}else{
    // 		this.queryParams.fNumber=''
    // 		this.form.deptId=undefined
    // 		this.$message({
    // 			showClose: true,
    // 			message:'只能查询设备',
    // 			type: 'warning'
    // 		});
    // 	}
    // },
    treeValueChange (val) {
      if (val == null || val == undefined || val == '') {
        return
      }
      if (val.length > 8) {
        this.queryParams.fNumber = val
        this.existPrograms()
      } else {
        this.queryParams.fNumber = ''
        this.$message({
          showClose: true,
          message: '只能查询设备',
          type: 'warning'
        })
        let that = this
        setTimeout(function () {
          that.form.deptId = undefined
        }, 100)
      }
    },
    // 查询部门下拉树结构
    getTreeselect () {
      getDev(this.quer2)
        .then(response => {
          // console.log(response.data)
          this.mapTreeData = response.data
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      if (selection.length > 0) {
        this.ids[0] = selection[0].fPNo
        this.cards = selection.map(item => item.fNumber)
      }
      if (selection.length === 1) {
        this.sendShow2 = false
      } else {
        this.sendShow2 = true
      }
    },
    // 节目下架
    handPull () {
      console.log(this.cards)
      if (this.cards.length > 0) {
        this.$confirm('确定要下架选中节目吗？', '节目下架', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            pullProgram({
              cardList: this.cards,
              command: 47,
              idList: this.ids
            }).then(res => {
              if (res.code == 200) {
                let that = this
                this.$message({
                  showClose: true,
                  type: 'success',
                  message: '节目下架中'
                })
                setTimeout(function () {
                  that.existPrograms()
                }, 1000)
              } else {
                this.$message.error(res.msg)
              }
            })
          })
          .catch(() => {
            this.$message({
              showClose: true,
              type: 'info',
              message: '已取消下架'
            })
          })
      } else {
        this.$message({
          showClose: true,
          type: 'info',
          message: '请选择需要下架的节目'
        })
      }
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 查询设备存在节目
    async existPrograms () {
      const res = await exist(
        this.addDateRange(this.queryParams, this.dateRange)
      )
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
        this.tableData.forEach((item, index) => {
          this.tableData[index].fTaskSpeed =
            (item.fTaskSpeed ? item.fTaskSpeed : 0) +
            '/' +
            (item.fTaskBag ? item.fTaskBag : 0)
        })
      }
    },
    // 搜索
    handleQuery2 () {
      this.queryParams.pageNum = 1
      let reg = /^[0-9]{4,6}$/
      // console.log(this.queryParams.fPId)
      if (
        this.queryParams.fPId == undefined ||
        this.queryParams.fPId == null ||
        this.queryParams.fPId == ''
      ) {
        this.sendShow = true
        return
      } else if (reg.test(this.queryParams.fPId)) {
        this.existPrograms()
        this.sendShow = false
      } else {
        this.sendShow = true
      }
    },
    handleQuery () {
      this.queryParams.pageNum = 1
      this.queryParams.fNumber = this.form.deptId
      this.existPrograms()
    },
    /** 重置按钮操作 */
    resetQuery () {
      // this.dateRange = [] // 清空日期选择器
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 表格存在设备格式化内容
    deviceFormatter (row, column, cellValue, index) {
      let deviceName = ''
      switch (cellValue) {
        case 0:
          deviceName = '不存在'
          break
        case 1:
          deviceName = '存在'
          break
        default:
          break
      }
      return deviceName
    },
    // 表格状态格式化内容
    statusFormatter (row, column, cellValue, index) {
      let typeName = ''
      switch (cellValue) {
        case 0:
          typeName = '等待发送'
          break
        case 4:
          typeName = '发送成功'
          break
        case 10:
          typeName = '发送失败'
          break
        case 11:
          typeName = '任务覆盖'
          break
        default:
          break
      }
      return typeName
    }
  },
  mounted () {
    this.tableHeight =
      this.$refs.consDom.offsetHeight - this.$refs.colDom.offsetHeight - 100
    this.isTable = true
  },
  beforeRouteLeave (to, from, next) {
    this.$route.query.id = undefined
    next()
  },
  activated () {
    if (this.$route.query.id && this.$store.state.programId) {
      this.queryParams.fPId = this.$store.state.programId
      this.sendShow = false
    } else {
      this.sendShow = true
    }
    if (this.$store.state.deptId) {
      this.quer2.deptId = this.$store.state.deptId // 把点击获得的id赋值给queryParams模型id
      this.queryParams.deptId = this.$store.state.deptId
      this.getTreeselect()
      this.existPrograms()
    }
    // else{
    // 	this.queryParams.fPId=undefined
    // 	this.sendShow=true
    // }
  },
  watch: {
    // 根据名称筛选部门树
    deptName (val) {
      this.$refs.tree.filter(val)
    },
    deptOptions: {
      handler () {
        this.deptOptions.forEach(item => {
          this.expandeds.push(item.id)
        })
      },
      deep: true
    },
    '$store.state.deptId': {
      handler (newval) {
        this.queryParams.deptId = newval // 把点击获得的id赋值给queryParams模型id
        this.quer2.deptId = newval
        this.queryParams.fNumber = this.form.deptId
        this.getTreeselect()
        this.existPrograms()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
	::v-deep.devList-top {
		height: 45px;
		width:400px;
		display: flex;
		border-radius: 5px;
		line-height: 45px;
		span {
			font-weight: 700;
			font-size: 14px;
		}
		.el-form {
			width:28%;
			top: 3px;
			left:77px;
			z-index: 999;
			position: absolute;
		}
		.vue-treeselect__menu{
			overflow-x: auto;
			width:310px;
		}
		
		.vue-treeselect div, .vue-treeselect span{
		box-sizing:content-box;
		}
	}
</style>
